package com.qiyang.contoller;

import com.qiyang.entity.UserVo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;
import java.util.List;

/**
 * Created on 2020/12/11.
 *
 * @author qiyang.
 * 描述：
 */
@Controller
@RequestMapping("converter")
public class ConverterController {

    /**
     * 类型转换器演示
     * @param userVo
     * @return
     */
    @GetMapping("test")
    public String test(@Valid UserVo userVo, BindingResult result) {
        System.out.println(userVo);
        return "show";
    }

    /**
     * 校验演示
     * 加上BindingResult 可以让前端不报错，代表自己处理错误信息
     * @param userVo
     * @return
     */
    @PostMapping("login")
    public String login(@Valid UserVo userVo, BindingResult result, Model model) {

        /**
         * 将错误信息获取到，输出到视图上
         */
        if(result.hasErrors()) {
            // Map<String, String> model = new HashMap<String, String>();
            List<FieldError> fieldErrors = result.getFieldErrors();
            // 转成map到页面显示更佳
            fieldErrors.forEach(field->{
                model.addAttribute(field.getField(), field.getDefaultMessage());
            });
            return "login";
        }

        System.out.println(userVo);
        return "show";
    }
}
